package com.run_java_test.test6;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarClassLoader extends URLClassLoader {

    private final List<Class<?>> loadedClasses = new ArrayList<>();

    public JarClassLoader(URL jarUrl) {
        super(new URL[]{jarUrl}, Thread.currentThread().getContextClassLoader());
    }

    public List<Class<?>> loadAllClasses(String packagePrefix) throws IOException {
        List<Class<?>> classes = new ArrayList<>();
        try (JarFile jarFile = new JarFile(getURLs()[0].getFile())) {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (entry.getName().endsWith(".class")) {
                    String className = entry.getName()
                            .replace("/", ".")
                            .replace(".class", "");
                    if (className.startsWith(packagePrefix)) {
                        try {
                            Class<?> clazz = loadClass(className);
                            classes.add(clazz);
                            loadedClasses.add(clazz);
                        } catch (ClassNotFoundException e) {
                            System.err.println("Failed to load class: " + className);
                        }
                    }
                }
            }
        }
        return classes;
    }

    public List<Class<?>> getLoadedClasses() {
        return loadedClasses;
    }
}
